package com.example.graduation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.graduation.entity.Evaluate;
import com.example.graduation.entity.Shop;
import com.example.graduation.entity.Torder;
import com.example.graduation.entity.User;
import com.example.graduation.exception.MyException;
import com.example.graduation.mapper.EvaluateMapper;
import com.example.graduation.mapper.OrderMapper;
import com.example.graduation.mapper.ShopMapper;
import com.example.graduation.mapper.UserMapper;
import com.example.graduation.service.EvaluateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.graduation.util.JwtUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xyc
 * @since 2022-02-11
 */
@Service
public class EvaluateServiceImpl extends ServiceImpl<EvaluateMapper, Evaluate> implements EvaluateService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private EvaluateMapper evaluateMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;


    /**
     * 查找用户的所有评论列表
     *
     * @param token
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Evaluate> findAllEvaluate(String token, Integer page, Integer size) {
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 8;
        }
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).orderByDesc("order_id");
            Page<Evaluate> evaluatePage = evaluateMapper.selectPage(new Page<>(page, size), wrapper);
            return evaluatePage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }


    /**
     * 查询已经评论或者没有完成评论的列表（这里表示用户没有删除的列表）
     *
     * @param token
     * @param status 评论状态，用于判断评论是否已经完成
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Evaluate> findDownEvaluate(String token, Integer status, Integer page, Integer size) {
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 8;
        }
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("status", status).eq("isdelete", 0).orderByDesc("order_id");
            Page<Evaluate> evaluatePage = evaluateMapper.selectPage(new Page<>(page, size), wrapper);
            return evaluatePage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查找失败");
        }
    }


    /**
     * 查看评论的具体内容
     *
     * @param id
     * @return {@link Evaluate}
     * @author xieyucan
     * CreateDate 2022/3/22 17:56
     */
    @Override
    public Evaluate findEvaluate(Integer id) {
        try {
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Evaluate evaluate = evaluateMapper.selectOne(wrapper);
            if (evaluate == null) {
                throw new MyException("查找失败");
            }
            return evaluate;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查找失败");
        }
    }


    /**
     * 对商品进行评价，在这里，只是针对商品文字评价，
     * 文字评价和文字图片评价分开接口写，其中图片为单独接口书写
     *
     * @param id
     * @param orderId
     * @param content
     * @param type    为数字拼接 0好 1良 2中 3一般 4差
     * @param title   为数字拼接 0质量好 1配送快 2味道好 3性价比高 4很好看
     * @return {@link Evaluate}
     * @author xieyucan
     * CreateDate 2022/3/22 18:20
     */
    @Override
    public Evaluate downEvaluate(Integer id, String orderId, String content, Integer type, String title, String token) {
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Evaluate evaluate = evaluateMapper.selectOne(wrapper);
            if (evaluate == null) {
                throw new MyException("查找失败");
            }
            if (userId == evaluate.getUserId()) {
                evaluate.setContent(content);
                evaluate.setTitle(title);
                evaluate.setType(type);
                evaluateMapper.update(evaluate, wrapper);
                return evaluate;
            } else {
                throw new MyException("给用户没有评论权限");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 根据评论id删除评论,用户可以删除自己的列表，但所在的评论还是存在的
     *
     * @param id
     * @return {@link Boolean}
     * @author xieyucan
     * CreateDate 2022/3/23 9:14
     */
    @Override
    public Boolean deleteEvaluate(Integer id) {
        try {
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Evaluate evaluate = evaluateMapper.selectOne(wrapper);
            evaluate.setIsdelete(1);
            /**
             * 在更新这里。尝试一下不用UpdateQuery看是否可行
             */
            int update = evaluateMapper.update(evaluate, wrapper);
            if (update > 0) {
                return true;
            } else {
                throw new MyException("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 查找商品被评论的列表
     *
     * @param shopId
     * @return {@link Page< Evaluate>}
     * @author xieyucan
     * CreateDate 2022/3/23 9:31
     */
    @Override
    public Page<Evaluate> findShopEvaluate(Integer shopId, Integer page, Integer size) {
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 8;
        }
        try {
            QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
            wrapper.eq("shop_id", shopId);
            Page<Evaluate> evaluatePage = evaluateMapper.selectPage(new Page<>(page, size), wrapper);
            return evaluatePage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查找失败");
        }
    }


    /**
     * 商家回复该评论
     * 逻辑：本店回复对本店的评论
     *
     * @return {@link Evaluate}
     * @author xieyucan
     * CreateDate 2022/3/23 9:32
     */
    @Override
    public Evaluate replyEvaluate(Evaluate evaluate, String token) {
        try {
            int userId = jwtUtil.getUserIdByToken(token);
            Integer shopId = evaluate.getShopId();
            QueryWrapper<Shop> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("shop_id", shopId);
            Shop shop = shopMapper.selectOne(wrapper1);
            if (userId == shop.getUserId()) {
                UpdateWrapper<Evaluate> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", evaluate.getId());
                int update = evaluateMapper.update(evaluate, wrapper);
                if (update > 0) {
                    return evaluate;
                } else {
                    throw new MyException("回复失败");
                }
            } else {
                throw new UnauthorizedException("权限不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 评价
     *
     * @param token
     * @param orderId
     * @param photo
     * @param content
     * @return
     */
    public Evaluate pinglun(String token, Long orderId, String photo, String content) {
        Evaluate evaluate = new Evaluate();
        int userId = jwtUtil.getUserIdByToken(token);
        QueryWrapper<Torder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        Torder torder = orderMapper.selectOne(wrapper);
        evaluate.setContent(content);
        evaluate.setShopId(torder.getShopId());
        evaluate.setOrderId(orderId);
        evaluate.setPhoto(photo);
        evaluate.setUserId(userId);
        evaluate.setStatus(1);
        evaluateMapper.insert(evaluate);
        return evaluate;
    }


    /**
     * 获取商家评论
     *
     * @param shopId
     * @return
     */
    public List<Evaluate> findShopEvaluate(Integer shopId) {
        QueryWrapper<Evaluate> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", shopId);
        List<Evaluate> evaluates = evaluateMapper.selectList(wrapper);
        for (Evaluate evaluate : evaluates) {

            User user = userMapper.selectById(evaluate.getUserId());
            evaluate.setUser(user);
        }
        return evaluates;
    }
}
